import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useDataModelStore = defineStore('dataModel', () => {
  // 数据源
  const dataSources = ref([
    {
      id: 'sample_data',
      name: '示例数据',
      type: 'json',
      status: 'connected',
      description: '内置示例数据集',
      connectionString: '',
      tables: [
        {
          id: 'employees',
          name: '员工表',
          description: '员工基本信息',
          rowCount: 8,
          position: { x: 100, y: 100 },
          fields: [
            { id: 'id', name: 'ID', dataType: 'number', category: '维度', isPrimaryKey: true, isForeignKey: false, isCalculated: false },
            { id: 'name', name: '姓名', dataType: 'text', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'age', name: '年龄', dataType: 'number', category: '度量值', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'department_id', name: '部门ID', dataType: 'number', category: '维度', isPrimaryKey: false, isForeignKey: true, isCalculated: false },
            { id: 'salary', name: '薪资', dataType: 'currency', category: '度量值', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'city', name: '城市', dataType: 'text', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'hire_date', name: '入职日期', dataType: 'date', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false }
          ]
        },
        {
          id: 'departments',
          name: '部门表',
          description: '部门信息',
          rowCount: 3,
          position: { x: 500, y: 100 },
          fields: [
            { id: 'id', name: 'ID', dataType: 'number', category: '维度', isPrimaryKey: true, isForeignKey: false, isCalculated: false },
            { id: 'name', name: '部门名称', dataType: 'text', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'manager', name: '部门经理', dataType: 'text', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'budget', name: '预算', dataType: 'currency', category: '度量值', isPrimaryKey: false, isForeignKey: false, isCalculated: false }
          ]
        },
        {
          id: 'projects',
          name: '项目表',
          description: '项目信息',
          rowCount: 5,
          position: { x: 300, y: 400 },
          fields: [
            { id: 'id', name: 'ID', dataType: 'number', category: '维度', isPrimaryKey: true, isForeignKey: false, isCalculated: false },
            { id: 'name', name: '项目名称', dataType: 'text', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'department_id', name: '部门ID', dataType: 'number', category: '维度', isPrimaryKey: false, isForeignKey: true, isCalculated: false },
            { id: 'start_date', name: '开始日期', dataType: 'date', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'end_date', name: '结束日期', dataType: 'date', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'budget', name: '项目预算', dataType: 'currency', category: '度量值', isPrimaryKey: false, isForeignKey: false, isCalculated: false },
            { id: 'status', name: '状态', dataType: 'text', category: '维度', isPrimaryKey: false, isForeignKey: false, isCalculated: false }
          ]
        }
      ]
    }
  ])

  // 表关系
  const relationships = ref([
    {
      id: 'emp_dept',
      name: '员工-部门关系',
      fromTable: 'employees',
      fromField: 'department_id',
      toTable: 'departments',
      toField: 'id',
      type: 'many-to-one',
      crossFilterDirection: 'single',
      isActive: true
    },
    {
      id: 'dept_proj',
      name: '部门-项目关系',
      fromTable: 'projects',
      fromField: 'department_id',
      toTable: 'departments',
      toField: 'id',
      type: 'many-to-one',
      crossFilterDirection: 'single',
      isActive: true
    }
  ])

  // 计算字段
  const calculatedFields = ref([
    {
      id: 'annual_salary',
      name: '年薪',
      table: 'employees',
      expression: '[salary] * 12',
      dataType: 'currency',
      category: '度量值',
      description: '员工年薪计算'
    },
    {
      id: 'age_group',
      name: '年龄组',
      table: 'employees',
      expression: 'IF([age] < 30, "青年", IF([age] < 50, "中年", "老年"))',
      dataType: 'text',
      category: '维度',
      description: '根据年龄分组'
    }
  ])

  // 数据源模板
  const dataSourceTemplates = ref([
    {
      id: 'excel_template',
      name: 'Excel文件',
      type: 'excel',
      icon: 'Document',
      description: '从Excel文件导入数据',
      fields: [
        { name: 'file', label: '文件路径', type: 'file', required: true },
        { name: 'sheet', label: '工作表', type: 'text', required: false },
        { name: 'hasHeader', label: '包含标题行', type: 'boolean', default: true }
      ]
    },
    {
      id: 'csv_template',
      name: 'CSV文件',
      type: 'csv',
      icon: 'Document',
      description: '从CSV文件导入数据',
      fields: [
        { name: 'file', label: '文件路径', type: 'file', required: true },
        { name: 'delimiter', label: '分隔符', type: 'select', options: [',', ';', '\t'], default: ',' },
        { name: 'encoding', label: '编码', type: 'select', options: ['UTF-8', 'GBK', 'GB2312'], default: 'UTF-8' }
      ]
    },
    {
      id: 'database_template',
      name: '数据库连接',
      type: 'database',
      icon: 'Grid',
      description: '连接到数据库',
      fields: [
        { name: 'host', label: '主机地址', type: 'text', required: true },
        { name: 'port', label: '端口', type: 'number', default: 3306 },
        { name: 'database', label: '数据库名', type: 'text', required: true },
        { name: 'username', label: '用户名', type: 'text', required: true },
        { name: 'password', label: '密码', type: 'password', required: true }
      ]
    },
    {
      id: 'api_template',
      name: 'API接口',
      type: 'api',
      icon: 'Connection',
      description: '从API接口获取数据',
      fields: [
        { name: 'url', label: 'API地址', type: 'text', required: true },
        { name: 'method', label: '请求方法', type: 'select', options: ['GET', 'POST'], default: 'GET' },
        { name: 'headers', label: '请求头', type: 'textarea', required: false },
        { name: 'params', label: '参数', type: 'textarea', required: false }
      ]
    }
  ])

  // 计算属性
  const modelTables = computed(() => {
    return dataSources.value.flatMap(ds => ds.tables || [])
  })

  const allFields = computed(() => {
    return modelTables.value.flatMap(table => 
      table.fields.map(field => ({
        ...field,
        tableName: table.name,
        tableId: table.id
      }))
    )
  })

  const dimensionFields = computed(() => {
    return allFields.value.filter(field => field.category === '维度')
  })

  const measureFields = computed(() => {
    return allFields.value.filter(field => field.category === '度量值')
  })

  // 方法
  const addDataSource = (dataSource) => {
    const newDataSource = {
      id: Date.now().toString(),
      ...dataSource,
      status: 'connected',
      tables: dataSource.tables || []
    }
    dataSources.value.push(newDataSource)
    return newDataSource
  }

  const updateDataSource = (id, updates) => {
    const index = dataSources.value.findIndex(ds => ds.id === id)
    if (index !== -1) {
      dataSources.value[index] = {
        ...dataSources.value[index],
        ...updates
      }
    }
  }

  const removeDataSource = (id) => {
    const index = dataSources.value.findIndex(ds => ds.id === id)
    if (index !== -1) {
      dataSources.value.splice(index, 1)
    }
  }

  const addTable = (dataSourceId, table) => {
    const dataSource = dataSources.value.find(ds => ds.id === dataSourceId)
    if (dataSource) {
      const newTable = {
        id: Date.now().toString(),
        ...table,
        position: table.position || { x: 100, y: 100 },
        fields: table.fields || []
      }
      if (!dataSource.tables) {
        dataSource.tables = []
      }
      dataSource.tables.push(newTable)
      return newTable
    }
  }

  const updateTable = (tableId, updates) => {
    for (const dataSource of dataSources.value) {
      if (dataSource.tables) {
        const index = dataSource.tables.findIndex(t => t.id === tableId)
        if (index !== -1) {
          dataSource.tables[index] = {
            ...dataSource.tables[index],
            ...updates
          }
          break
        }
      }
    }
  }

  const removeTable = (tableId) => {
    for (const dataSource of dataSources.value) {
      if (dataSource.tables) {
        const index = dataSource.tables.findIndex(t => t.id === tableId)
        if (index !== -1) {
          dataSource.tables.splice(index, 1)
          break
        }
      }
    }
    // 同时删除相关的关系
    relationships.value = relationships.value.filter(
      rel => rel.fromTable !== tableId && rel.toTable !== tableId
    )
  }

  const addField = (tableId, field) => {
    const table = modelTables.value.find(t => t.id === tableId)
    if (table) {
      const newField = {
        id: Date.now().toString(),
        ...field,
        isPrimaryKey: field.isPrimaryKey || false,
        isForeignKey: field.isForeignKey || false,
        isCalculated: field.isCalculated || false
      }
      table.fields.push(newField)
      return newField
    }
  }

  const updateField = (tableId, fieldId, updates) => {
    const table = modelTables.value.find(t => t.id === tableId)
    if (table) {
      const index = table.fields.findIndex(f => f.id === fieldId)
      if (index !== -1) {
        table.fields[index] = {
          ...table.fields[index],
          ...updates
        }
      }
    }
  }

  const removeField = (tableId, fieldId) => {
    const table = modelTables.value.find(t => t.id === tableId)
    if (table) {
      const index = table.fields.findIndex(f => f.id === fieldId)
      if (index !== -1) {
        table.fields.splice(index, 1)
      }
    }
    // 同时删除相关的关系
    relationships.value = relationships.value.filter(
      rel => rel.fromField !== fieldId && rel.toField !== fieldId
    )
  }

  const addRelationship = (relationship) => {
    const newRelationship = {
      id: Date.now().toString(),
      ...relationship,
      isActive: relationship.isActive !== false
    }
    relationships.value.push(newRelationship)
    return newRelationship
  }

  const updateRelationship = (id, updates) => {
    const index = relationships.value.findIndex(rel => rel.id === id)
    if (index !== -1) {
      relationships.value[index] = {
        ...relationships.value[index],
        ...updates
      }
    }
  }

  const removeRelationship = (id) => {
    const index = relationships.value.findIndex(rel => rel.id === id)
    if (index !== -1) {
      relationships.value.splice(index, 1)
    }
  }

  const addCalculatedField = (calculatedField) => {
    const newField = {
      id: Date.now().toString(),
      ...calculatedField
    }
    calculatedFields.value.push(newField)
    
    // 同时添加到对应的表中
    const table = modelTables.value.find(t => t.id === calculatedField.table)
    if (table) {
      table.fields.push({
        id: newField.id,
        name: newField.name,
        dataType: newField.dataType,
        category: newField.category,
        isPrimaryKey: false,
        isForeignKey: false,
        isCalculated: true
      })
    }
    
    return newField
  }

  const updateCalculatedField = (id, updates) => {
    const index = calculatedFields.value.findIndex(cf => cf.id === id)
    if (index !== -1) {
      calculatedFields.value[index] = {
        ...calculatedFields.value[index],
        ...updates
      }
    }
  }

  const removeCalculatedField = (id) => {
    const index = calculatedFields.value.findIndex(cf => cf.id === id)
    if (index !== -1) {
      const calculatedField = calculatedFields.value[index]
      calculatedFields.value.splice(index, 1)
      
      // 同时从表中删除
      const table = modelTables.value.find(t => t.id === calculatedField.table)
      if (table) {
        const fieldIndex = table.fields.findIndex(f => f.id === id)
        if (fieldIndex !== -1) {
          table.fields.splice(fieldIndex, 1)
        }
      }
    }
  }

  const getTableData = (tableId) => {
    // 这里应该根据实际的数据源获取数据
    // 暂时返回示例数据
    const sampleData = {
      'employees': [
        { id: 1, name: '张三', age: 25, department_id: 1, salary: 8000, city: '北京', hire_date: '2024-01-15' },
        { id: 2, name: '李四', age: 30, department_id: 2, salary: 6500, city: '上海', hire_date: '2024-01-16' },
        { id: 3, name: '王五', age: 28, department_id: 1, salary: 9500, city: '深圳', hire_date: '2024-01-17' },
        { id: 4, name: '赵六', age: 35, department_id: 3, salary: 7200, city: '广州', hire_date: '2024-01-18' },
        { id: 5, name: '钱七', age: 26, department_id: 1, salary: 8800, city: '杭州', hire_date: '2024-01-19' },
        { id: 6, name: '孙八', age: 32, department_id: 2, salary: 7000, city: '成都', hire_date: '2024-01-20' },
        { id: 7, name: '周九', age: 29, department_id: 3, salary: 6800, city: '武汉', hire_date: '2024-01-21' },
        { id: 8, name: '吴十', age: 27, department_id: 1, salary: 9200, city: '西安', hire_date: '2024-01-22' }
      ],
      'departments': [
        { id: 1, name: '技术部', manager: '张经理', budget: 500000 },
        { id: 2, name: '销售部', manager: '李经理', budget: 300000 },
        { id: 3, name: '市场部', manager: '王经理', budget: 200000 }
      ],
      'projects': [
        { id: 1, name: '项目A', department_id: 1, start_date: '2024-01-01', end_date: '2024-06-30', budget: 100000, status: '进行中' },
        { id: 2, name: '项目B', department_id: 2, start_date: '2024-02-01', end_date: '2024-08-31', budget: 150000, status: '进行中' },
        { id: 3, name: '项目C', department_id: 1, start_date: '2024-03-01', end_date: '2024-12-31', budget: 200000, status: '计划中' },
        { id: 4, name: '项目D', department_id: 3, start_date: '2024-01-15', end_date: '2024-05-15', budget: 80000, status: '已完成' },
        { id: 5, name: '项目E', department_id: 2, start_date: '2024-04-01', end_date: '2024-10-31', budget: 120000, status: '进行中' }
      ]
    }
    return sampleData[tableId] || []
  }

  const validateRelationship = (relationship) => {
    const fromTable = modelTables.value.find(t => t.id === relationship.fromTable)
    const toTable = modelTables.value.find(t => t.id === relationship.toTable)
    
    if (!fromTable || !toTable) {
      return { valid: false, message: '表不存在' }
    }
    
    const fromField = fromTable.fields.find(f => f.id === relationship.fromField)
    const toField = toTable.fields.find(f => f.id === relationship.toField)
    
    if (!fromField || !toField) {
      return { valid: false, message: '字段不存在' }
    }
    
    if (fromField.dataType !== toField.dataType) {
      return { valid: false, message: '字段类型不匹配' }
    }
    
    return { valid: true, message: '关系有效' }
  }

  const refreshModel = () => {
    // 刷新数据模型，重新加载数据源
    console.log('刷新数据模型')
  }

  const exportModel = () => {
    // 导出数据模型配置
    return {
      dataSources: dataSources.value,
      relationships: relationships.value,
      calculatedFields: calculatedFields.value
    }
  }

  const importModel = (modelConfig) => {
    // 导入数据模型配置
    if (modelConfig.dataSources) {
      dataSources.value = modelConfig.dataSources
    }
    if (modelConfig.relationships) {
      relationships.value = modelConfig.relationships
    }
    if (modelConfig.calculatedFields) {
      calculatedFields.value = modelConfig.calculatedFields
    }
  }

  return {
    // 状态
    dataSources,
    relationships,
    calculatedFields,
    dataSourceTemplates,
    
    // 计算属性
    modelTables,
    allFields,
    dimensionFields,
    measureFields,
    
    // 数据源方法
    addDataSource,
    updateDataSource,
    removeDataSource,
    
    // 表方法
    addTable,
    updateTable,
    removeTable,
    
    // 字段方法
    addField,
    updateField,
    removeField,
    
    // 关系方法
    addRelationship,
    updateRelationship,
    removeRelationship,
    validateRelationship,
    
    // 计算字段方法
    addCalculatedField,
    updateCalculatedField,
    removeCalculatedField,
    
    // 数据方法
    getTableData,
    
    // 模型方法
    refreshModel,
    exportModel,
    importModel
  }
})
